<template>
  <el-drawer
    v-bind="$attrs"
    class="sv-el-drawer"
    ref="drawerRef"
    @open="openDrawer"
    @close="closeDrawer"
    destroy-on-close
    :close-on-click-modal="false"
  >
    <template #header>
      <h3>{{ formMode == 'add' ? '新增' : '编辑' }}</h3>
    </template>
    <template #default>
      <el-form
        class="sv-el-form"
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
        label-position="left"
      >
        <el-form-item prop="lib_id" label="题库ID" required>
          <el-input v-model="formData.lib_id" placeholder="请输入题库ID" clearable />
        </el-form-item>
        <el-form-item prop="lib_name" label="题库名称" required>
          <el-input v-model="formData.lib_name" placeholder="请输入题库名称" clearable />
        </el-form-item>
        <el-form-item prop="lib_title" label="题库标题">
          <el-input v-model="formData.lib_title" placeholder="请输入题库标题" clearable />
        </el-form-item>
        <el-form-item prop="intro" label="题库介绍">
          <el-input
            v-model="formData.intro"
            type="textarea"
            :autosize="{ minRows: 2 }"
            placeholder="请输入题库介绍"
          />
        </el-form-item>
        <el-form-item prop="lib_chapter" label="题库章节">
          <sv-dynamic-input
            v-model:data="formData.lib_chapter"
            labelWidth="70px"
            textAlign="left"
            lableText="章节ID"
            valueText="章节名称"
            keyPlaceholder="请输入章节ID"
            valuePlaceholder="请输入章节名称"
          >
            <template #default="{ data }">
              <view class="flex-vc">
                <text class="flex-shrink-0" style="width: 70px">章节简介</text>
                <input
                  type="text"
                  class="dynamic-input"
                  v-model="data.content"
                  placeholder="请输入章节简介"
                />
              </view>
            </template>
          </sv-dynamic-input>
        </el-form-item>
        <el-form-item prop="origin" label="题库来源">
          <el-input v-model="formData.origin" placeholder="请输入题库来源" clearable />
        </el-form-item>
        <el-form-item prop="befit" label="适用范围">
          <el-input v-model="formData.befit" placeholder="请输入适用范围" clearable />
        </el-form-item>
        <el-form-item prop="profession" label="所属职业">
          <sv-dict-select
            v-model="formData.profession"
            placeholder="请选择所属职业"
            :dictList="professionDictList"
            keyName="profession_name"
            valueName="profession_id"
          ></sv-dict-select>
        </el-form-item>
        <el-form-item prop="icon" label="图标">
          <sv-icon-select v-model:icon="formData.icon"></sv-icon-select>
        </el-form-item>
        <el-form-item prop="vip" label="VIP特权">
          <el-switch
            v-model="formData.vip"
            style="--el-switch-on-color: #67C23A; --el-switch-off-color: #909399"
            inline-prompt
            :active-icon="Check"
            :inactive-icon="Close"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item prop="comment" label="备注">
          <el-input
            v-model="formData.comment"
            type="textarea"
            :autosize="{ minRows: 2 }"
            placeholder="请输入备注"
          />
        </el-form-item>
        <el-form-item prop="total" label="试题总数">
          <el-input-number class="sv-el-input-number" v-model="formData.total" :min="0" />
        </el-form-item>
        <el-form-item prop="price" label="定价">
          <el-input-number
            class="sv-el-input-number"
            v-model="formData.price"
            :min="0"
            :step="10"
          />
          <text class="margin-left text-cyan">
            =&nbsp;{{ convertFenToYuan(formData.price) }}&nbsp;元
          </text>
        </el-form-item>
        <el-form-item prop="discount" label="折扣">
          <el-input-number
            class="sv-el-input-number"
            v-model="formData.discount"
            :min="0"
            :step="10"
          />
          <text class="margin-left text-cyan">
            =&nbsp;{{ convertFenToYuan(formData.discount) }}&nbsp;元
          </text>
        </el-form-item>
        <el-form-item prop="sell_num" label="销售量">
          <el-input-number
            class="sv-el-input-number"
            v-model="formData.sell_num"
            :min="0"
            disabled
          />
        </el-form-item>
        <el-form-item prop="fav_num" label="收藏量">
          <el-input-number
            class="sv-el-input-number"
            v-model="formData.fav_num"
            :min="0"
            disabled
          />
        </el-form-item>
        <el-form-item prop="sort" label="排序">
          <el-input-number class="sv-el-input-number" v-model="formData.sort" :min="0" />
        </el-form-item>
        <el-form-item prop="banner" label="轮播图">
          <sv-file-upload
            ref="fileUploadRef"
            :file="formData.banner"
            file-mediatype="image"
            @success="successUpload"
          ></sv-file-upload>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="confirm">确认</el-button>
    </template>
  </el-drawer>
</template>

<script setup>
import { ref, watchEffect } from 'vue'
import { convertFenToYuan } from '@/uni_modules/sv-exam-plus/utils'
import { professionList } from '@/service/api/profession.js'
import { Check, Close } from '@element-plus/icons-vue'

const props = defineProps({
  formInit: {
    type: Object,
    default: {}
  },
  formMode: {
    type: String,
    default: 'add'
  }
})

const emits = defineEmits(['submit'])

// 表单数据
const formData = ref({})
// 初始数据
const formBase = {
  lib_id: '', // 题库id
  lib_name: '', // 题库名称
  lib_title: '', // 题库标题
  intro: '', // 介绍
  origin: '', // 题库来源说明
  befit: '', // 适用范围说明
  lib_chapter: [{ key: 'unit-1', value: '第一单元', content: '第一单元介绍' }], // 题库章节
  profession: '', // 所属职业
  icon: '', // 图标
  comment: '', // 备注
  vip: 0, // 是否是VIP特权题库 0普通 1特权
  total: 0, // 题库包含的试题总数
  price: 0, // 价格(分) 100分 = 1元
  discount: 0, // 折扣(分) 100分 = 1元
  sort: 0, // 题库顺序
  sell_num: 0, // 销售量
  fav_num: 0, // 收藏量
  banner: [] // 横幅轮播展示图
}

watchEffect(() => {
  // 表单数据初始化更新
  formData.value = Object.assign({ ...formBase }, props.formInit)
})

// 校验规则
const rules = ref({
  lib_id: [{ required: true, message: '请输入题库ID', trigger: 'blur' }],
  lib_name: [{ required: true, message: '请输入题库名称', trigger: 'blur' }]
})

const drawerRef = ref() // 抽屉
const formRef = ref() // 表单

function openDrawer() {
  if (props.formMode == 'edit') {
    // 联表对象需要单独处理 - 提取出profession_id
    formData.value.profession = props.formInit?.profession[0]?.profession_id
  }
}

function closeDrawer() {}

const fileUploadRef = ref()

// 关闭抽屉
function cancel() {
  drawerRef.value.handleClose()
}

// 文件上传成功
function successUpload(e) {
  formData.value.banner = e
  // 需要等上传结束后再提交
  emits('submit', { data: formData.value, mode: props.formMode })
  drawerRef.value.handleClose()
}

// 确认提交表单
function confirm() {
  formRef.value.validate(async (valid, fields) => {
    if (valid) {
      fileUploadRef.value.uploadFiles()
      // 后续逻辑都需要在successUpload中执行
    } else {
      console.log('==== 校验失败 :', fields)
    }
  })
}

const professionDictList = ref([])
async function handleDictList() {
  const professionlistRes = await professionList()
  professionDictList.value = professionlistRes.data || []
}
handleDictList()
</script>

<style lang="scss">
.dynamic-input {
  border: 1px solid #cccccc;
  width: 100%;
  height: calc(var(--dynamic-input-size) * 2);
  padding: 0 calc(var(--dynamic-input-size) / 2);
  border-radius: 4px;
  font-size: inherit;
}
</style>
